package com.stuffthathappens.concurrency;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @author Eric Burke
 */
public class LatchDemo {
    private static final int NUM_THREADS = 10;

    public static void main(String[] args) throws InterruptedException {
        final CountDownLatch startGate = new CountDownLatch(1);
        final CountDownLatch endGate = new CountDownLatch(NUM_THREADS);

        for (int i=0; i<NUM_THREADS; i++) {
            Thread t = new Thread() {
                public void run() {
                    try {
                        startGate.await();
                        System.out.println("start");

                        // simulate doing some work for a second
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        // ignored
                    } finally {
                        endGate.countDown();

                        System.out.println("stop");
                    }
                }
            };
            t.start();
        }

        long startTime = System.nanoTime();

        // start all of the threads at the same time
        startGate.countDown();

        // wait for all threads to complete
        endGate.await();

        long endTime = System.nanoTime();

        double ms = (endTime - startTime) / 1000000.0;

        System.out.format("Elapsed time = %.2fms%n", ms);
    }


}
